#include<iostream>
#include<unistd.h>
#include<cstdio>
#include<cstring>
#include<sys/wait.h>
#include<sys/types.h>

#define MAXSIZE 128
char*  g_argv[MAXSIZE];

#define CommandSize 1024
#define FORMAT "[%s@%s %s]# "

const char* GetHOSTNAME()
{
  const char* name = getenv("HOSTNAME");
  return name == NULL ? "NONE" : name;
}

const char* GetUSER()
{
  const char* user = getenv("USER");
  return user == NULL ? "NONE" : user;
}

const char* GetPWD()
{
  const char* pwd = getenv("PWD");
  return pwd == NULL ? "NONE" : pwd;
}

std::string Dirname(const char* pwd)
{
#define Sign "/"
  std::string dir = pwd;
  if(dir == Sign) return Sign;

  auto pos = dir.rfind(Sign);
  if(pos == std::string::npos) return "Bug?";

  return dir.substr(pos + 1);
}

void MakecmdLine(char cmd_prompt[],int size)
{
  snprintf(cmd_prompt,size,FORMAT,GetUSER(),GetHOSTNAME(),Dirname(GetPWD()).c_str());
}


void PrintcmdLine()
{
  char cmd_pro[CommandSize];

  MakecmdLine(cmd_pro,sizeof(cmd_pro));

  printf("%s",cmd_pro);
}



bool CommandCut(char* CmdLine)
{
#define sign " "
  int g_argc = 0;
  g_argv[g_argc++] =  strtok(CmdLine,sign);
  
  while((bool)(g_argv[g_argc++] = strtok(nullptr,sign)));

  g_argc--;
  return true;
}

int execute()
{
	pid_t id = fork();
	if(id == 0)
	{
		execvp(g_argv[0],g_argv);
		exit(1);
	}	
	pid_t rid = waitpid(id,nullptr,0);
	(void)rid;//使用一下rid,避免报错

	return 0;
}

bool GetCmd(char* cmd,int size)
{
    char* c = fgets(cmd,size,stdin);
    
    if(c == NULL) return false;
   
    cmd[strlen(cmd) - 1] = 0;
		if(strlen(cmd) == 0) return false;
		
		return true;
}

int main()
{
  // printf("[%s@%s %s]#",GetUSER(),GetHOSTNAME(),GetPWD());
 PrintcmdLine();
	while(true)
	{
		char CommandLine[CommandSize];
		if(!GetCmd(CommandLine, sizeof(CommandLine)))
    continue;

		CommandCut(CommandLine);
		execute();
	}	

  return 0;
}
